document.addEventListener('DOMContentLoaded', () => {
    const folderTree = document.getElementsByClassName('folder-tree')[0];
    const fileList = document.getElementsByClassName('file-list')[0];
    const previewDiv = document.getElementsByClassName('preview')[0];
    const preImageDiv = document.querySelector('#one-img');
    const longImageDiv = document.querySelector('#long-img');
	
	const scrollContent = document.getElementById('tab1');
	
	const searchTxt = document.getElementById('code-search');
	const historyList = document.getElementById('historyList');
	const clearSearchBtn = document.getElementById('clear-search-btn');
	
	const randmPlayBtn = document.getElementById('randm_play_btn');
	const openPlayBtn = document.getElementById('open_play_btn');

    let selItem = null;
	let selUrl = null;
    let selFolder = null;

    // ******************************************************************************************************************************************************
    //#region tree
    // Function to build the folder tree
    function findDestFolder(bookmarks, parentId = 0){
        let destBookmark = null;

        for (let bookmark of bookmarks){
            if (bookmark.title.includes("av-old")){
                destBookmark = bookmark;
                break;
            }

            if (bookmark.children) {
                destBookmark = findDestFolder(bookmark.children, bookmark.id);
                if(destBookmark){
                    break;
                }
            }
        }

        return destBookmark;
    }

    function createFolderElement(bookmark, parentId){
        const li = document.createElement('li');
        li.classList.add('folder');
        li.textContent = bookmark.title;
        li.dataset.id = bookmark.id;
        li.dataset.parentId = parentId;

        li.addEventListener('dblclick', function (event){
            const chilUl = li.querySelector('ul');

            if (chilUl){
                li.removeChild(chilUl);
            }else {
                childUl = buildFolderTree(bookmark.children, bookmark.id);
                li.appendChild(childUl);
            }

            event.stopPropagation();
        });

        li.addEventListener('click', (event) => {
            if (selFolder){
                selFolder.style.removeProperty('background-color');
            }
            selFolder = li;
            selFolder.style.backgroundColor = '#d58282';

            queryBookmarkList(bookmark.id);

            event.stopPropagation();
        });

        return li;
    }

    function isExpandClass(bookmarks){
        for (let bookmark of bookmarks){
            if (bookmark.children){
                return true;
            }
        }

        return false;
    }

    function createFolderElement2(bookmark, parentId){
        const div = document.createElement('div');
        div.classList.add('tree-row');
        div.dataset.id = bookmark.id;
        div.dataset.parentId = parentId;

        const expand = document.createElement('span');
        expand.classList.add('expand');
        expand.addEventListener('click', function (event){
            const chilUl = div.querySelector('div');

            if (chilUl){
                div.removeChild(chilUl);
                expand.style.transform = 'rotate(-90deg)';
            }else {
                childUl = buildFolderTree2(bookmark.children, bookmark.id);
                div.appendChild(childUl);
                expand.style.transform = 'rotate(0)';
            }

            event.stopPropagation();
        });
        div.appendChild(expand);
        if (isExpandClass(bookmark.children)){
            expand.style.visibility = 'visible';
        }else {
            expand.style.visibility = 'hidden';
        }

        const lable = document.createElement('span');
        lable.classList.add('folder');
        lable.textContent = bookmark.title;
        div.appendChild(lable);

        div.addEventListener('dblclick', function (event){
            const chilUl = div.querySelector('div');

            if (chilUl){
                div.removeChild(chilUl);
                expand.style.transform = 'rotate(-90deg)';
            }else {
                childUl = buildFolderTree2(bookmark.children, bookmark.id);
                div.appendChild(childUl);
                expand.style.transform = 'rotate(0)';
            }

            event.stopPropagation();
        });

        div.addEventListener('click', (event) => {
            if (selFolder){
                let lable = selFolder.querySelector('.folder');
                lable.style.removeProperty('background-color');
            }
            selFolder = div;
            let lable = selFolder.querySelector('.folder');
            lable.style.backgroundColor = '#d58282';

            queryBookmarkList(bookmark);

            event.stopPropagation();
        });

        return div;
    }

    function buildFolderTree2(bookmarks, parentId = 0) {
        const ul = document.createElement('div');
        ul.classList.add('tree-children');
        bookmarks.forEach(bookmark => {
            if (bookmark.children) {
                const li = createFolderElement2(bookmark, parentId);

                ul.appendChild(li);
            }

        });
        return ul;
    }

    function buildFolderTree(bookmarks, parentId = 0) {
        const ul = document.createElement('ul');
        bookmarks.forEach(bookmark => {
            if (bookmark.children) {
                const li = createFolderElement(bookmark, parentId);

                ul.appendChild(li);
            }

        });
        return ul;
    }

    //#endregion

    let inputTimer = null;

    // ******************************************************************************************************************************************************
    //#region list
    let searchNode = {};
    async function searchBookmarkList(searchStr){
        let tabs = await chrome.tabs.query({active: true, currentWindow: true});
        let currentTab = tabs[0].url;

        if (currentTab.includes('anxia') || currentTab.includes('115vod')){
            urlRegex = /anxia|115vod/i;
        }

        chrome.history.search({
            text: searchStr,
            maxResults: 200,
            startTime: 0,
            endTime: Date.now()
        }, (historyItems) => {
            searchNode.children = [];

            for (let i=0; i<historyItems.length; i++) {
                const item = historyItems[i];
                // 过滤网站
                if (!urlRegex.test(item.url)){
                    continue;
                }

                removeStringAndAfter(item, '_115');

                searchNode.children.push(item);
            }

            console.log(searchNode);

            searchNode.isDay = true;
            queryBookmarkList(searchNode);
        });
    }

    function queryBookmarkList(folder){
        if (folder.isDay){
            writeLastItems(folder);

            updateFileList(folder.children)
        }
    }

    // Function to update the file list
    function updateFileList(nodes) {
        fileList.innerHTML = '';

        nodes.forEach(bookmark => {
            if (bookmark.children) return;
			
			if (!urlRegex.test(bookmark.url)){
				return;
			}

            const bookmarkTitle2 = bookmark.title.replace(".HD", "").replace(".FHD", "").replace(".txt", "").replace(/[a-zA-Z0-9]+\.[a-zA-Z]{2,3}/g, '');
            const regex = /[a-zA-Z]{2,5}-?[0-9]{2,5}/;
            const match = bookmarkTitle2.match(regex);
            let avcode = null;
            if (match && match[0]) {
                avcode = match[0].toUpperCase();
            }

            if (!avcode) return;

            const li = document.createElement('li');
            // li.textContent = bookmark.title;
            li.dataset.id = bookmark.id;

            let splitArr = splitSpan(bookmark.title);
            if (splitArr.length > 1){
                const spanCode = document.createElement('span');
                spanCode.style.color = '#42af1c';
                spanCode.style.fontSize = "90%";
                spanCode.textContent = splitArr[0];
                li.appendChild(spanCode);

                const spanName= document.createElement('span');
                spanName.style.color = '#186060';
                spanName.style.fontSize = "110%";
                spanName.textContent = splitArr[1];
                li.appendChild(spanName);

                const spanStar= document.createElement('span');
                spanStar.style.color = '#6d6dda';
                spanStar.style.fontSize = "90%";
                spanStar.textContent = splitArr[2];
                li.appendChild(spanStar);
            }else {
                li.textContent = bookmark.title;
            }

            let javicon = 'other.png';
            if (bookmark.url.includes('anxia') || bookmark.url.includes('115vod')){
                javicon = 'anxia.png';
            }else if (bookmark.url.includes('bus')){
                javicon = 'bus.png';
            }else if (bookmark.url.includes('javdb')){
                javicon = 'javdb.png';
            }

            li.style = `
                // background-image: url(chrome://favicon/size/16@1x/${bookmark.url});
                background-image: url(icons/${javicon});
                background-repeat: no-repeat;
                background-size: 16px;
            `;

            if (bookmark.sel){
                li.style.backgroundColor = '#e7caca';
            }

            li.addEventListener('click', () => {
                if (selItem){
                    selItem.style.removeProperty('background-color');
                    selItem.dataset.sel = false;
                }
                selItem = li;
                selItem.style.backgroundColor = '#e7caca';
                selItem.dataset.sel = true;
				
				selUrl = bookmark.url;

                previewBookmark(bookmark.title);
            });

            li.addEventListener('dblclick', () => {
                let url = bookmark.url;
				
				if (!currentUrl){
					 window.open(url, '_blank');
				}
				
                if (currentUrl.includes('bus') || currentUrl.includes('javdb')){
                    let codeText2 = formatCodeForNone(avcode);
                    let url = `https://webapi.115.com/files/search?search_value=${codeText2}&format=json`;

                    window.open(url, '_blank'); // 在新标签页中打开URL

				}else if (url.includes('anxia')){
					url = url.replace('v.anxia.com', '115vod.com');
                    chrome.tabs.update(undefined, {url: url});
                    chrome.runtime.sendMessage({action: 'hidePopup'});
					window.close();
					
                }else if (url.includes('115vod')){
                    chrome.tabs.update(undefined, {url: url});
                    chrome.runtime.sendMessage({action: 'hidePopup'});
					window.close();

                }else {
                    window.open(url, '_blank');
                }


            });

            fileList.appendChild(li);
        });
    }

    //#endregion

    // ******************************************************************************************************************************************************
    //#region content

    // Function to preview the bookmark
    function previewBookmark(bookmarkTitle) {
        const bookmarkTitle2 = bookmarkTitle.replace(".HD", "").replace(".FHD", "").replace(".txt", "").replace(/[a-zA-Z0-9]+\.[a-zA-Z]{2,3}/g, '');
        // 使用正则表达式匹配文件名
        const regex = /[a-zA-Z]{2,5}-?[0-9]{2,5}/;
        const match = bookmarkTitle2.match(regex);
        let avcode = null;
        // const previewUrl = 'https://www.cd120.com.cn/thumb/assets/addons/cms/img/noimage/503/288.jpg';
        let previewUrl = `http://localhost:10168/preview/defult.jpg`;

        // 如果找到匹配项，将其作为键存入 Map
        // 注意：这里我们假设每个匹配的文件名都是唯一的，或者我们只关心第一个匹配项
        if (match && match[0]) {
            avcode = match[0].toUpperCase();
        }

        if (!avcode) return;

        // 增加预览视频
        let newCode = formatCode(avcode);
		
		startRequest(avcode, "历史");
		
        // let videoSrc = "https://fivetiu.com/" + newCode.toLowerCase() + "/preview.mp4";
        // let preVideo = previewDiv.querySelector('#pre-video');
        // preVideo.src = videoSrc;

        // 增加大预览图
        let imgSrc = "https://pedia-bucket-image.xfuse.fun/covers/" + newCode.toUpperCase() + ".jpg";
        let img = previewDiv.querySelector('#pre-img');
        img.style.width = '100%';
        img.src = imgSrc;

        // 增加预览图列表
        preImageDiv.innerHTML = '';
        searchFileList_javbus(newCode, 'preview', preImgCallback, finishCallback);


		// 增加长预览图
        longImageDiv.innerHTML = '';
        // searchFileList(false, avcode, 'longimg', longImgCallback);
		
		function preImgCallback(ret, imgName){
            if (ret == 1) {
                let avcode_00 = formatCodeFor00(newCode);
                previewUrl = `https://spic.hotoss.com/dmm/digital/video/${avcode_00}/${avcode_00}jp-${imgName}.jpg`;

            } else if (ret == 2) {
                previewUrl = imgName;

            } else if (ret == 0) {
                previewUrl = `http://localhost:10168/preview/${imgName}`;
				
			} else if (ret == 3) {
                previewUrl = `http://localhost:10168/preview/fengetiao.jpg`;

            } else {
                previewUrl = `http://localhost:10168/preview/error.jpg`;
            }

            let previewImg = document.createElement('img');
            previewImg.classList.add('preview-img');
            previewImg.classList.add('lazyload');
            previewImg.dataset.src = previewUrl;
            previewImg.src = 'http://localhost:10168/longimg/img_loading.jpg';

            preImageDiv.appendChild(previewImg);

        }

        function finishCallback(res) {
            // 监听滚动事件
            lazyLoadImages(scrollContent);

        }
		
    }

    function loadImage(img, filePath){
        var xhr = new XMLHttpRequest();
        xhr.open('GET', filePath, true);
        xhr.responseType = 'blob';
        xhr.onload = function(e) {
            if (this.status === 200) {
                var blob = this.response;
                var reader = new FileReader();
                reader.onloadend = function() {
                    // var img = new Image();
                    img.src = reader.result;
                    // document.body.appendChild(img);
                };
                reader.readAsDataURL(blob);
            }
        };
        xhr.send();
    }
	
	function startRequest(avcode, fromStr) {
        let url = `http://localhost:10168/startrequest?avcode=${avcode}&fromstr=${fromStr}`;

        // 使用 fetch 发送 GET 请求
        fetch(url)
            .then(response => {
                // 检查响应是否成功
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                // 解析JSON
                return ;
            })
            .catch(error => {
                // 处理请求过程中出现的错误
                console.error('fetch error:', error);
            });

    }

    function searchFileList(isOther, javCode, cls, callback, callFinish = null) {
        //保存查询关键词参数
        //GM_setValue("115_search_var", `${javId}|${javId2}|${javId3}|${javId4}`);

        let url = null;
        if (cls === 'preview') {
            url = `http://localhost:10168/search?imgcode=${javCode}`;
        } else if (cls === 'longimg') {
            url = `http://localhost:10168/longsearch?imgcode=${javCode}`;
        }
        if (!url) return;

        // 使用 fetch 发送 GET 请求
        fetch(url)
            .then(response => {
                // 检查响应是否成功
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                // 解析JSON
                return response.json();
            })
            .then(resultJson => {
                // 处理JSON数据
                if (resultJson.length > 0) {

                    for (let i = 0; i < resultJson.length; i++) {
                        let row = resultJson[i];

                        if (row) {
                            callback(0, row);
                        }
                    }
                    return true;

                }else {
                    throw new Error('Element not found');
                }

            })
            .then(res => {
                // if (callFinish) {
                    // setTimeout(function () {
                        // callFinish(res);
                    // }, 500);
                // }
				
				callback(3, null);
				searchFileList_mfinder(javCode, cls, callback, callFinish);
				
            })
            .catch(error => {
                // 处理请求过程中出现的错误
                console.error('fetch error:', error);
                if (isOther && error.message === 'Network response was not ok') {
                    searchFileList_mfinder(javCode, cls, callback, callFinish);

                } else if (isOther && error.message === 'Element not found') {
                    searchFileList_mfinder(javCode, cls, callback, callFinish);

                } else {
                    callback(-1, null);
                }
            });

    }

    function searchFileList_tor05(javCode, cls, callback, callFinish = null) {
        // 请求URL
        // const url = 'http://localhost:10168/proxy?target_url=https://tor05.com/en/videos/' + javCode.toLowerCase();
        const url = 'http://localhost:10168/site/tor05/' + javCode.toLowerCase() + '.html';

        // 使用fetch API发送请求
        fetch(url)
            .then(response => {
                // 检查响应是否成功
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                // 将响应转换为文本（如果是HTML页面）
                return response.text();
            })
            .then(html => {
                // 创建一个DOM解析器
                const parser = new DOMParser();
                // 将HTML字符串解析为DOM文档
                const doc = parser.parseFromString(html, 'text/html');
                // 查询特定的元素
                const imgAaalist = doc.querySelectorAll('#preview-img .glightbox2');
                // 处理查询到的元素
                if (imgAaalist && imgAaalist.length > 0) {
                    console.log('Found element:', imgAaalist);
                    // 你可以在这里对elements进行进一步处理，比如获取其属性或内容
                    for (let i = 0; i < imgAaalist.length; i++) {
                        let aaa = imgAaalist[i];
                        callback(2, aaa.href);
                    }
                    return true;

                } else {
                    throw new Error('Element not found');
                }
            }).then(res => {
            if (callFinish) {
                setTimeout(function () {
                    callFinish(res);
                }, 500);
            }

        }).catch(error => {
            // 处理错误
            console.error('fetch error:', error);
            if (error.message === 'Network response was not ok') {
                callback(-1, null);

            } else if (error.message === 'Element not found') {
                callback(-1, null);

            } else {
                callback(-1, null);
            }
        });
    }

    function searchFileList_mfinder(javCode, cls, callback, callFinish = null) {
        // 请求URL
        // const url = 'http://localhost:10168/proxy?target_url=https://tor05.com/en/videos/' + javCode.toLowerCase();
        const url = 'http://localhost:10168/site/mfinder/' + javCode.toLowerCase() + '.html';

        // 使用fetch API发送请求
        fetch(url)
            .then(response => {
                // 检查响应是否成功
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                // 将响应转换为文本（如果是HTML页面）
                return response.text();
            })
            .then(html => {
                // 创建一个DOM解析器
                const parser = new DOMParser();
                // 将HTML字符串解析为DOM文档
                const doc = parser.parseFromString(html, 'text/html');
                // 查询特定的元素
                const imglist = doc.querySelectorAll('.card-body .screenshot-link img');
                // 处理查询到的元素
                if (imglist && imglist.length > 0) {
                    console.log('Found element:', imglist);
                    // 你可以在这里对elements进行进一步处理，比如获取其属性或内容
                    let imgArr = Array.from(imglist);
                    imgArr.sort((a, b) => {
                        let anum = a.src.match(/-(\d{1,2}).jpg/)[1];
                        let bnum = b.src.match(/-(\d{1,2}).jpg/)[1];

                        return anum - bnum;
                    });
                    for (let i = 0; i < imgArr.length; i++) {
                        let img = imgArr[i];
                        imgAddrs = img.src.split('?');
                        callback(2, imgAddrs[0]);
                    }
                    return true;

                } else {
                    throw new Error('Element not found');


                }
            }).then(res => {
            if (callFinish) {
                setTimeout(function () {
                    callFinish(res);
                }, 500);
            }

        }).catch(error => {
            // 处理错误
            console.error('fetch error:', error);
            if (error.message === 'Network response was not ok') {
                searchFileList_javbus(javCode, cls, callback, callFinish);

            } else if (error.message === 'Element not found') {
                searchFileList_javbus(javCode, cls, callback, callFinish);

            } else {
                callback(-1, null);
            }
        });
    }

    function searchFileList_javbus(javCode, cls, callback, callFinish = null) {
        // 请求URL
        // const url = 'http://localhost:10168/proxy?target_url=https://tor05.com/en/videos/' + javCode.toLowerCase();
        const url = 'http://localhost:10168/site/javbus/' + javCode.toLowerCase() + '.html';

        // 使用fetch API发送请求
        fetch(url)
            .then(response => {
                // 检查响应是否成功
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                // 将响应转换为文本（如果是HTML页面）
                return response.text();
            })
            .then(html => {
                // 创建一个DOM解析器
                const parser = new DOMParser();
                // 将HTML字符串解析为DOM文档
                const doc = parser.parseFromString(html, 'text/html');
                // 查询特定的元素
                const imgAaalist = doc.querySelectorAll('#sample-waterfall a');
                // 处理查询到的元素
                if (imgAaalist && imgAaalist.length > 0) {
                    console.log('Found element:', imgAaalist);
                    // 你可以在这里对elements进行进一步处理，比如获取其属性或内容
                    for (let i = 0; i < imgAaalist.length; i++) {
                        let aaa = imgAaalist[i];
                        callback(2, aaa.href);
                    }
                    return true;

                } else {
                    throw new Error('Element not found');


                }
            }).then(res => {
            if (callFinish) {
                setTimeout(function () {
                    callFinish(res);
                }, 500);
            }

        }).catch(error => {
            // 处理错误
            console.error('fetch error:', error);
            if (error.message === 'Network response was not ok') {
                searchFileList_tor05(javCode, cls, callback, callFinish);

            } else if (error.message === 'Element not found') {
                searchFileList_tor05(javCode, cls, callback, callFinish);

            } else {
                callback(-1, null);
            }
        });
    }
	
	// 懒加载逻辑
    function lazyLoadImages(scroolElement) {
        let lazyLoadThrottleTimeout;

        // 检查内容是否在可视窗口内
        function isInViewport(element) {
            let top = element.offsetTop - scrollContent.scrollTop;
            if(top < (window.innerHeight * 2)) {
                return true;
            }

            return false;
        }

        function lazyLoad() {
            if(lazyLoadThrottleTimeout) {
                clearTimeout(lazyLoadThrottleTimeout);
            }

            lazyLoadThrottleTimeout = setTimeout(function() {
                const images = document.querySelectorAll('.lazyload');
                images.forEach(img => {
                    if (img.src.includes('img_loading.jpg') && isInViewport(img)) {
                        // const source = img.getAttribute('data-src');
                        const source = img.dataset.src;
                        img.src = source;
                        // img.removeAttribute('data-src');
                        img.classList.remove('lazyload');
                    }
                });

                if(images.length == 0) {
                    scroolElement.removeEventListener("scroll", lazyLoad);
                    scroolElement.removeEventListener("resize", lazyLoad);
                    scroolElement.removeEventListener("orientationChange", lazyLoad);
                }
            }, 200);
        }

        lazyLoad();
        scroolElement.addEventListener("scroll", lazyLoad);
        scroolElement.addEventListener("resize", lazyLoad);
        scroolElement.addEventListener("orientationChange", lazyLoad);
    }

    //#endregion

    // ******************************************************************************************************************************************************
    //#region Common
    function formatCode(code){
        let newCode = code;
        if (code.indexOf('-') == -1){
            let numbers = code.match(/\d+/g);
            let chars = code.match(/[a-zA-Z]+/g);

            if (numbers && chars){
                newCode = chars[0] + "-" + numbers[0];
            }
        }

        return newCode;
    }

    function formatCodeForNone(code){
        let newCode = code;
        if (code.indexOf('-') == -1){
            let numbers = code.match(/\d+/g);
            let chars = code.match(/[a-zA-Z]+/g);

            if (numbers && chars){
                newCode = chars[0] + "%20" + numbers[0];
            }
        }

        return newCode;
    }

    function removeStringAndAfter(item, searchStr) {
        // 查找searchStr在str中的位置
        const index = item.title.indexOf(searchStr);
        if (index !== -1) {
            // 使用slice从0到searchStr的位置（不包括searchStr）切片字符串
            item.title = item.title.slice(0, index);
        }
    }

    // 读取书签
    // chrome.bookmarks.getTree((treeNodes) => {
    //     let avold = findDestFolder(treeNodes[0].children);
    //     if (!avold) return;
    //
    //     const rootUl = buildFolderTree2(avold.children);
    //     folderTree.appendChild(rootUl);
    //     // updateFileList(treeNodes[0].children[0].id); // Default to the first folder
    // });

    let nodeList = {};
    let rootNode = {};
    function generateNode(item, parentId, parentTitle, parentOfparentId, parentOfparentTitle){
        if (!nodeList[parentOfparentId]){
            const newNode = {};
            newNode.id = parentOfparentId;
            newNode.title = parentOfparentTitle;
            newNode.children = [];

            nodeList[newNode.id] = newNode;

            newNode.parentId = 'root';
            rootNode.children.push(newNode);
        }

        if (!nodeList[parentId]){
            const newNode = {};
            newNode.id = parentId
            newNode.title = parentTitle;
            newNode.isDay = true;
            newNode.children = [];

            nodeList[newNode.id] = newNode;

            nodeList[parentId].parentId = parentOfparentId;
            nodeList[parentOfparentId].children.push(nodeList[parentId]);
        }
		
		if (!nodeList[item.id]){
            nodeList[item.id] = item;
			nodeList[item.id].parentId = parentId;
        }
        nodeList[parentId].children.push(nodeList[item.id]);

    }
	
	function getRandomInt(min, max) {
		min = Math.ceil(min);
		max = Math.floor(max);
		
		return Math.floor(Math.random() * (max - min + 1)) + min;
	}

    function getStar(title){
        let stars = title.match(/[=]{1,2}(.+)\./);

        if (stars && stars[1]){
            return stars[1].replace(/[=【】\s]+/g, '');
        }

        return null;
    }

    function uniqueArray(array){
        const uniqueArr = array.reduce((accumulator, current) => {
            const exist = accumulator.find(item => item.title === current.title);
            if (!exist) {
                accumulator.push(current);
            }
            return accumulator;
        }, []);

        return uniqueArr;
    }

    function splitSpan(str){
        let splitArr = [];

        let index1 = -1;
        let matchs = str.match(/ |(---)/);
        if (matchs && matchs.index){
            index1 = matchs.index;
        }

        if (index1 > 0){
            splitArr.push(str.substring(0, index1));
        }

        let index2 = str.lastIndexOf('=');
        let index3 = str.lastIndexOf('.');
        if (index2 > 0 && index3 > 0){
            splitArr.push(str.substring(index1, index2));
            splitArr.push(str.substring(index2, index3));
        }
        if (index2 < 0 && index3 > 0){
            splitArr.push(str.substring(index1, index3));
        }

        return splitArr;
    }

    function writeLastItems(node){
        // 将对象转换为JSON字符串并存储在localStorage中
        chrome.storage.local.set({last_items: JSON.stringify(node)}, function() {
            console.log('Object stored successfully');
        });
    }

    function readLastItems(callback){
        chrome.storage.local.get('last_items', function(result) {
            if (result.last_items) {
                // 从JSON字符串解析为对象
                const node = JSON.parse(result.last_items);
                callback(node);
            } else {
                callback(null);
                console.log('No data found');
            }
        });
    }

    function readClipboard() {
        var content = "";
        navigator.clipboard.readText()
            .then(function(text){
                content = text;
            })
            .catch(function(error){
                console.error('Failed to read clipboard contents: ', error);
            });
        return content;
    }

    //#endregion


    // ******************************************************************************************************************************************************
    //#region TopTools

    const colNum = document.getElementById('col-num');
    const lastItemsBtn = document.getElementById('last-items');
    function initTopPanel() {

        colNum.addEventListener('input', function (event) {
            let colNum = event.target.value;

            preImageDiv.style.gridTemplateColumns = `repeat(${colNum},auto)`;
        });

        lastItemsBtn.addEventListener('click', function (event){
            readLastItems(function (node){
                if (node != null){
                    updateFileList(node.children);
                }
            });
        });

        const tabButtons = document.querySelectorAll('.tab-button');
        const tabContents = document.querySelectorAll('.tab-content');

        tabButtons.forEach(button => {
            button.addEventListener('click', function () {
                const targetTab = this.getAttribute('data-tab');

                // Hide all tab contents
                tabContents.forEach(content => {
                    content.style.display = 'none';
                });

                document.getElementById(targetTab).style.removeProperty('display');

                // Optionally, remove active class from all buttons and add to the clicked button
                tabButtons.forEach(btn => btn.classList.remove('active'));
                this.classList.add('active');
            });
        });

        let addBookmarkBtn = document.querySelector('#add_bookmark');
        addBookmarkBtn.addEventListener('click', function (event){
            let text = readClipboard();
            let bookmarkObj = JSON.parse(text);

            if (bookmarkObj && bookmarkObj.addbookmark){
                chrome.bookmarks.create(bookmarkObj.addbookmark, function (result){
                    console.log('add bookmark result: ' + result);
                    alert('add bookmark result: ' + result);
                });
            }

        });
		
		randmPlayBtn.addEventListener('click', function(event){
			let liEles = fileList.querySelectorAll('li');
			if (!liEles) return;
			
			let liLen = liEles.length;
			let index = Math.floor(Math.random() * liLen);
			
			let randmLi = liEles[index];
			if (!randmLi) return;
			
			// randmLi.scrollIntoView({ behavior: "smooth" });
			
			// 创建一个新的鼠标双击事件
			var dblClickEvent = new MouseEvent('dblclick', {
				view: window,
				bubbles: true,
				cancelable: true
			});
		 
			// 模拟双击
			randmLi.dispatchEvent(dblClickEvent);
			
		});
		
		openPlayBtn.addEventListener('click', function(event){
			
			if (!selUrl){
				 return;
			}
			
			if (selUrl.includes('bus') || selUrl.includes('javdb')){
				let codeText2 = formatCodeForNone(avcode);
				let url = `https://webapi.115.com/files/search?search_value=${codeText2}&format=json`;

				window.open(url, '_blank'); // 在新标签页中打开URL

			}else if (selUrl.includes('anxia')){
				url = url.replace('v.anxia.com', '115vod.com');
				window.open(selUrl, '_blank');
				chrome.runtime.sendMessage({action: 'hidePopup'});
				
			}else if (selUrl.includes('115vod')){
				window.open(selUrl, '_blank');
				chrome.runtime.sendMessage({action: 'hidePopup'});

			}else {
				window.open(selUrl, '_blank');
			}
			
		});

        // 监听来自 content.js 的消息
        // chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
        //     console.log(request.greeting);  // 对收到的消息进行处理
        //     // sendResponse({ farewell: "ok" });  // 可以向 sender 发送回复（可选）
        // });

        // 添加事件监听器
        window.addEventListener('message', function (event){
            // event对象包含了接收到的消息和其他相关信息
            var message = event.data;
            var origin = event.origin;

            // 处理接收到的消息
            console.log('Received message: ' + message);
        });
    }

    //#endregion
	
	// ******************************************************************************************************************************************************
    //#region histroy
   
    function loadHistory() {
        const history = JSON.parse(localStorage.getItem('inputHistory')) || [];
        historyList.innerHTML = ''; // Clear previous options
        history.forEach((item, index) => {
            const option = document.createElement('option');
            option.value = item;
            historyList.appendChild(option);
        });
    }

    function saveHistory(history) {
        localStorage.setItem('inputHistory', JSON.stringify(history));
    }

    function updateHistory(newValue) {
        let history = JSON.parse(localStorage.getItem('inputHistory')) || [];
        const trimmedValue = newValue.trim();

        // Remove duplicates and trim empty strings
        history = history.filter(item => item.trim() !== '');
        history = [...new Set(history.map(item => item.trim()))];

        // Add new value if it's not already in the history
        // if (trimmedValue && !history.includes(trimmedValue)) {
            // history.unshift(trimmedValue); // Add to the beginning
            // if (history.length > 100) { // Limit the history size
                // history.pop(); // Remove the last item
            // }
        // }
		// 添加元素，如果存在则位置提前
		if (trimmedValue){
			let index = history.indexOf(trimmedValue);
			if (index !== -1) {
				// 移除元素
				history.splice(index, 1);
			}
			
			// 将元素添加到数组开头
			history.unshift(trimmedValue);
			if (history.length > 500) { // Limit the history size
                history.pop(); // Remove the last item
            }
		}

        saveHistory(history);
        loadHistory(); // Reload the datalist options
    }
	
	searchTxt.addEventListener('focus', function() {
	  // 焦点获取后执行的代码
	  loadHistory();
	  
	});

    searchTxt.addEventListener('blur', function () {
        updateHistory(searchTxt.value);
    });
	
	searchTxt.addEventListener('input', function (event) {
		let searchStr = event.target.value;

		clearTimeout(inputTimer);
		inputTimer = setTimeout(function () {
			searchBookmarkList(searchStr);
		}, 1000);

	});
	
	clearSearchBtn.addEventListener('click', function () {
		searchTxt.value = '';
    });

    //#endregion

	let currentUrl = null;
    let curTitle = null;
    let urlRegex = /bus|javdb|anxia|115vod/i;
    let curStar = null;
    let curStarNode = {};
    curStarNode.children = [];
    async function main(){
        let tabs = await chrome.tabs.query({active: true, currentWindow: true});
        currentUrl = tabs[0].url;
        curTitle = tabs[0].title;

        if (currentUrl.includes('anxia') || currentUrl.includes('115vod')){
            urlRegex = /anxia|115vod/i;

            curStar = getStar(curTitle);
        }

        chrome.history.search({
            text: '',
            maxResults: 20000,
            startTime: 0,
            endTime: Date.now()
        }, (historyItems) => {
            nodeList = {};
            rootNode = {};
            rootNode.id = 'root';
            rootNode.parentId = null;
            rootNode.children = [];
            nodeList[rootNode.id] = rootNode;
            let countNum = 0;

            for (let i=0; i<historyItems.length; i++) {
                const item = historyItems[i];
                // 过滤网站
                if (!urlRegex.test(item.url)){
                    continue;
                }

                if (curStar){
                    // curStarNode.children = [];
                    if (item.title.includes(curStar)){
                        curStarNode.children.push(item);
                        if (item.title === curTitle){
                            item.sel = true;
                        }
                    }
                }

                countNum++;

                removeStringAndAfter(item, '_115');

                // 创建目录tree
                const date = new Date(item.lastVisitTime);
                const yueId = date.getFullYear() + "-" + (date.getMonth()+1);
                const riId = yueId + "_" + date.getDate();
                const yueTitle = date.getFullYear() + '年' + (date.getMonth()+1) + '月';
                const riTitle = date.getDate() + '号';

                generateNode(item, riId, riTitle, yueId, yueTitle);

                // 最近100条
                if(countNum < 100){
                    generateNode(item, "last-100", "最近100条", "root", "");
                }
                let rmdInt = getRandomInt(1, 15);
                if(rmdInt <= 1){
                    generateNode(item, "random-100", "随机100条", "root", "");
                }

            }
            // chrome.storage.sync.set({ historyByDate });
            const rootUl = buildFolderTree2(rootNode.children);
            folderTree.appendChild(rootUl);

            console.log(nodeList);
            console.log(rootNode);

			// 更新左边列表显示
            curStarNode.children = uniqueArray(curStarNode.children);
            if (curStarNode.children.length >= 2){
                updateFileList(curStarNode.children);

            }else {
                readLastItems(function (node) {
                    if (node != null) {
                        updateFileList(node.children);
                    }
                });
            }
			
			// 更新内容显示
			previewBookmark(curTitle);

        });
    }

    initTopPanel();
    main();
});